import 'dart:convert';

import 'package:dio/dio.dart';

import 'dio_config.dart';

DioClient dioClient = DioClient();

class DioClient {
  late Dio _dio;
  late Dio _dioForDownload;

  DioClient() {
    _dio = Dio(BaseOptions(baseUrl: DioConfig.baseUrl, connectTimeout: const Duration(seconds: 10)));
    _dioForDownload = Dio();
  }

  setBaseUrl(String baseUrl) {
    _dio.options.baseUrl = baseUrl;
  }

  Future<Response> request(
    String url, {
    String method = "POST",
    Map<String, dynamic>? queryParameters,
    data,
    Map<String, dynamic>? headers,
  }) async {
    Options options = Options()
      ..method = method
      ..headers = headers;
    data = _convertRequestData(data);
    return await _dio.request(url, queryParameters: queryParameters, data: data, options: options);
  }

  _convertRequestData(data) {
    if (data != null) {
      data = jsonDecode(jsonEncode(data));
    }
    return data;
  }


  Future download(
    String url,
    String savePath, {
    Map<String, dynamic>? queryParams,
    CancelToken? cancelToken,
    void Function(int, int)? onReceiveProgress,
  }) async {
    return await _dioForDownload.download(
      url,
      savePath,
      queryParameters: queryParams,
      cancelToken: cancelToken,
      onReceiveProgress: onReceiveProgress,
    );
  }
}

